<template>
    <div>
        <div style="border: 1px solid #ccc; margin-top: 10px">
            <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"
                style="border-bottom: 1px solid #ccc" />
            <Editor :defaultConfig="editorConfig" :mode="mode" v-model="computedVla"
                style="height: 400px; overflow-y: hidden" @onCreated="handleCreated" @onChange="handleChange" />
        </div>
    </div>
</template>
  
<script setup>
import '@wangeditor/editor/dist/css/style.css';
import { onBeforeUnmount, ref, shallowRef, onMounted, defineEmits, defineProps, computed } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { DomEditor } from '@wangeditor/editor'
import { uploadImg } from '@/api/sys/upload'
const emit = defineEmits(['update:modelValue']);
const prop = defineProps({
    //表格
    modelValue: {
        type: String,
        default() {
            return '';
        },
    },

})

const computedVla = computed({
    get() {
        return prop.modelValue
    },
    set(value) {
        emit('update:modelValue', value); // 触发事件并传递新值
    }
})

// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref('');

// 模拟 ajax 异步获取内容
//   onMounted(() => {
//     setTimeout(() => {
//       valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>';
//     }, 1500);
//   });

const handleCustomUpload = (file, insertFn) => {
    // console.log("file", file);
    // JS 语法
    // file 即选中的文件
    // 自己实现上传，并得到图片 url alt href
    // 最后插入图片
    const formData = new FormData(); // 创建FormData对象来存储文件
    formData.append('file', file); // 将文件添加到FormData对象中，'file'是后端期望的字段名
    uploadImg(formData).then(res => {
        const imgUrl = "/api" + res.data.data.fileName
        insertFn(imgUrl, 'image', imgUrl)
    })
}


const toolbarConfig = { excludeKeys: ["group-video",], };
const editorConfig = {
    placeholder: '请输入内容...'
    , MENU_CONF: {
        uploadImage: {
            customUpload: handleCustomUpload
        }
    }

};

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;

    editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor) => {
    //console.log('created', editor);
    editorRef.value = editor; // 记录 editor 实例，重要！
    valueHtml.value = prop.modelValue
};
const handleChange = (editor) => {

    emit('update:modelValue', editor.getHtml()); // 触发事件并传递新值
    //console.log('change:', editor.getHtml());
};


</script>
  